#!/usr/bin/env bash

# 获取当前文件路径
dir=$(dirname "$0")
# 读取 .env 文件
source "$dir/.env"

echo "开始部署"
# 获取参数
token=$1
timestamp=$2
event=$3
ping=$4
secret="$WEBHOOK_SECRET"

# 输出参数以验证
#echo "X-Gitee-Token: $token"
#echo "X-Gitee-Timestamp: $timestamp"
## event: push_hooks、merge_request_hooks
#echo "X-Gitee-Event: $event"
#echo "X-Gitee-Ping: $ping"

# 计算 HMAC-SHA256，针对 Gitee
data=$(printf "%s\n%s" "$timestamp" "$secret")
hmac=$(echo -n "$data" | openssl dgst -sha256 -hmac "$secret" -binary | base64)

# 判断 $token === $hmac
if [ "$token" != "$hmac" ]; then
  echo "验签失败"
  exit 1
fi

# 判断是否为 ping 事件
if [ "$ping" = "true" ]; then
  echo "ping 事件"
  exit 0
fi

# 仅处理 push_hooks 和 merge_request_hooks 事件
if [ "$event" != "push_hooks" ] && [ "$event" != "merge_request_hooks" ]; then
  echo "忽略事件：$event"
  exit 1
fi